//
//  CHPickerView.m
//  CarFile
//
//  Created by 陈浩 on 2017/7/27.
//  Copyright © 2017年 陈浩. All rights reserved.
//

#import "CHPickerView.h"

@interface CHPickerView ()<UIPickerViewDelegate,UIPickerViewDataSource>

@property (nonatomic ,strong) NSMutableArray *yearArr;
@property (nonatomic ,strong) NSMutableArray *monthArr;

@property (nonatomic ,copy) NSString *yearStr;
@property (nonatomic ,copy) NSString *monthStr;
@property (nonatomic ,assign) BOOL isSelected;
/**
 *  日期选择器
 */
@property (nonatomic,weak) UIPickerView *pickerView;
/**
 *  遮盖按钮
 */
@property (nonatomic,strong) UIButton *cover;
@end

@implementation CHPickerView


- (UIButton *)cover {
    if (_cover == nil) {
        _cover = [[UIButton alloc] init];
        _cover.backgroundColor = [UIColor blackColor];
        _cover.alpha = 0.5;
        [_cover addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cover;
}


-(NSMutableArray *)yearArr{
    if (!_yearArr) {
        _yearArr = [[NSMutableArray alloc]init];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy"];
        NSString *yearStr = [formatter stringFromDate:[NSDate date]];
        int year = [yearStr intValue];
        for (int i = year - 3 ; i< year+1; i++) {
            NSString *str = [NSString stringWithFormat:@"%d%@",i,@"年"];
            [_yearArr addObject:str];
        }
    }
    return _yearArr;

}

-(NSMutableArray *)monthArr{
    if (!_monthArr) {
        self.monthArr = [[NSMutableArray alloc]init];
        for (int i = 1; i<13; i++) {
            NSString *str = [NSString stringWithFormat:@"%d%@",i,@"月"];
            [self.monthArr addObject:str];
        }
    }
    return _monthArr;
    
}

+(instancetype)pickerView{
    return [[CHPickerView alloc] init];
}

- (id)initWithCoder:(NSCoder *)aDecoder {

    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor whiteColor];
        _isSelected = NO;
        [self setup];
    }
    return self;
}

- (void)setup{
    
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW, 40)];
    bgView.backgroundColor = KRGB(44, 171, 203);
    [self addSubview:bgView];
    
    //取消
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, 0, 60, 40)];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [cancelBtn addTarget:self action:@selector(dismiss) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:cancelBtn];
    
    //  确定
    UIButton *sureBtn = [[UIButton alloc] initWithFrame:CGRectMake(UIScreenW - 40 -15, 0, 60, 40)];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:sureBtn];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 40, UIScreenW, 1)];
    line.backgroundColor = [UIColor colorWithHexString:@"999999" alpha:0.3];
    [self addSubview:line];
    
    
    //设置pickerview初始默认
    
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat:@"yyyy"];
    NSString *yearStr= [formatter1 stringFromDate:[NSDate date]];
    self.yearStr = [NSString stringWithFormat:@"%@年",yearStr];
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM"];
    NSString *monthStr = [formatter stringFromDate:[NSDate date]];
    self.monthStr = [NSString stringWithFormat:@"%.2d月",[monthStr intValue] -1];
    int month = [monthStr intValue];
    
    
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, UIScreenW, 200)];
    pickerView.dataSource = self;
    pickerView.delegate = self;
    [pickerView selectRow:month-2 inComponent:1 animated:NO];
    [pickerView selectRow:3 inComponent:0 animated:NO];
    [self addSubview:pickerView];
    self.pickerView = pickerView;
    
}


- (NSString *)getLastDate
{
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM"];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *lastMonthComps = [[NSDateComponents alloc] init];
    //    [lastMonthComps setYear:1]; // year = 1表示1年后的时间 year = -1为1年前的日期，month day 类推
    [lastMonthComps setMonth:-1];
    NSDate *newdate = [calendar dateByAddingComponents:lastMonthComps toDate:currentDate options:0];
    NSString *dateStr = [formatter stringFromDate:newdate];
    NSLog(@"date str = %@", dateStr);
    return dateStr;
}


-(void)sureBtnClick{
    NSString *dateStr = nil;
    if (_isSelected) {
        
        NSString *yearStr = [self.yearStr substringToIndex:4];
        
        NSString *monthStr = [NSString stringWithFormat:@"%.2d",[self.monthStr  intValue]];
        
        monthStr = [monthStr substringToIndex:2];
        
        dateStr = [NSString stringWithFormat:@"%@-%@",yearStr,monthStr];
        
    }else{
        
        dateStr = [self getLastDate];
        
    }
   
    
    if ([self.delegate respondsToSelector:@selector(pickerViewDidBackToDateStr:)]) {
        [self.delegate pickerViewDidBackToDateStr:dateStr];
    }

    [self dismiss];
    
}



/**
 *  显示日期选择器
 */
-(void)show{
    // 获得窗口
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    // 获得窗口的宽高
    CGFloat windowH = CGRectGetHeight(window.frame);
    CGFloat windowW = CGRectGetWidth(window.frame);
    // 设置当前view的高度
    CGFloat height = 240;
    
    // 添加遮盖按钮
    self.cover.frame = CGRectMake(0, 0,windowW , windowH);
    [window addSubview:self.cover];
    
    self.frame = CGRectMake(0, windowH, windowW, height);
    [window addSubview:self];
    [UIView animateWithDuration:0.25 animations:^{
        CGRect frame = self.frame;
        frame.origin.y = windowH - height;
        self.frame = frame;
    }];
    
}
/**
 *  隐藏日期选择器
 */
-(void)dismiss{
    // 获得窗口
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    // 获得窗口的高
    CGFloat windowH = CGRectGetHeight(window.frame);
    [UIView animateWithDuration:0.25 animations:^{
        CGRect frame = self.frame;
        frame.origin.y = windowH;
        self.frame = frame;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        // 移除遮盖
        [self.cover removeFromSuperview];
        _cover = nil;
    }];
}

- (void)dealloc {
    NSLog(@"dealloc---datePicker");
}




-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 2;
}


-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    _isSelected = YES;
    if (component == 0) {
        self.yearStr = self.yearArr[row];
        
    }else if(component == 1){

        self.monthStr = self.monthArr[row];
        
    }
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return 4;
    }else {
        return 12;
    }
}


- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    if (component == 0) {
        return  self.yearArr[row];
    }else {
        return  self.monthArr[row];
    }
}




@end
